package com.bx.implatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bx.implatform.config.GlobalDataManager;
import com.bx.implatform.entity.secondary.SecondaryChatScene;
import com.bx.implatform.entity.secondary.SecondaryUser;
import com.bx.implatform.mapper.secondary.SecondaryChatSceneMapper;
import com.bx.implatform.mapper.secondary.SecondaryUserMapper;
import com.bx.implatform.service.SecondaryChatSceneService;
import com.bx.implatform.service.SecondaryUserService;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SecondaryChatSceneServiceImpl extends ServiceImpl<SecondaryChatSceneMapper, SecondaryChatScene> implements SecondaryChatSceneService {

    private static final Logger logger = LoggerFactory.getLogger(SecondaryChatSceneServiceImpl.class);

    private final GlobalDataManager dataManager;

    public SecondaryChatSceneServiceImpl(GlobalDataManager dataManager) {
        this.dataManager = dataManager;
    }

    @Override
    public GlobalDataManager getDataManager() {
        return dataManager;
    }

    /**
     * 启动时自动拉取数据
     */
    @PostConstruct
    public void init() {
        loadChatScenes();
    }

    @Override
    public void loadChatScenes() {
        Map<String, Integer> keywordMap = new HashMap<>();

        QueryWrapper<SecondaryChatScene> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SecondaryChatScene::getValidFlag, true)
                .eq(SecondaryChatScene::getStatus, "1");

        List<SecondaryChatScene> sceneList = this.list(wrapper);
        Map<Integer, String[]> sceneMap = sceneList.stream().collect(Collectors.toMap(SecondaryChatScene::getId, scene -> scene.getKeywords().split("\n")));

        sceneMap.forEach((key, value) -> {
            for (String keyword:value) {
                keywordMap.put(keyword, key);
            }
        });
        dataManager.put("chatSceneKeywordMap", keywordMap);
    }

    @Override
    public Integer hitKeyword(String content) {
        Map<String, Integer> keywordMap = dataManager.get("chatSceneKeywordMap");
        for (String key:keywordMap.keySet()) {
            if (content.contains(key)) {
                return keywordMap.get(key);
            }
        }
        return 0;
    }

    @Override
    public SecondaryChatScene getChatScene(Integer id) {
        return this.getById(id);
    }

}
